import { FC, useState, useEffect } from 'react';
import {
  Space,
  Card,
  Table,
  Tag,
  Button,
  Form,
  Input,
  Select,
  Popconfirm,
  message,
  Pagination,
  Modal,
  DatePicker,
} from 'antd';
import request from 'umi-request';

import { TimeDate } from '@/utils/index';

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

/*
  列表接口
    method: POST
    url: http://pudge.wang:3000/api/cities/manage/list
    data: {
      page_size: 每页条数 number 10
      current_page: 当前第几页 number 1
    }
*/

/*
  城市接口
    method: GET
    url: http://pudge.wang:3000/api/cities/list
*/

/*
  删除接口
    method: POST
    url: http://pudge.wang:3000/api/cities/manage/del
    data: {
      id: 数据的_id string
    }
*/

/*
  新增接口
    method: POST
    url: http://pudge.wang:3000/api/cities/manage/add
    data: {
      admin: string
      city: string
      handleTime: number
      openTime: number
      operating: string
      useCar: string
    }
*/

const Index: FC = () => {
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [dataSource, setDataSource] = useState([]);
  const [total, setTotal] = useState(0);

  const [pageSize, setPageSize] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);

  const [cts, setCts] = useState([]);

  const [searchObj, setSearchObj] = useState({});

  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);

  const columns = [
    {
      title: 'id',
      dataIndex: '_id',
    },
    {
      title: '城市名称',
      dataIndex: 'city',
    },
    {
      title: '用车模式',
      dataIndex: 'useCar',
      render(text: string) {
        return <span>{text === '1' ? '禁停区' : '停车点'}</span>;
      },
    },
    {
      title: '营运模式',
      dataIndex: 'operating',
      render(text: string) {
        return <span>{text === '1' ? '自营' : '加盟'}</span>;
      },
    },
    {
      title: '城市管理员',
      dataIndex: 'admin',
    },
    {
      title: '城市开通时间',
      dataIndex: 'openTime',
      render(text: string) {
        return <span>{TimeDate(+text)}</span>;
      },
    },
    {
      title: '操作',
      render(text: string, record: any) {
        return (
          <Space>
            <Button type="dashed">修改</Button>
            <Popconfirm
              title="你确定要删除吗?"
              onConfirm={() => confirm(record)}
              okText="Yes"
              cancelText="No"
            >
              <Button danger>删除</Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    request
      .post('http://pudge.wang:3000/api/cities/manage/list', {
        data: {
          page_size: pageSize,
          current_page: currentPage,
          ...searchObj,
        },
      })
      .then((res) => {
        const result = res.result;
        const data = result.map((item: any) => {
          return {
            ...item,
            key: item._id,
          };
        });
        setDataSource(data);
        setTotal(res.total);
      });
  }, [pageSize, currentPage, searchObj]);

  useEffect(() => {
    request.get('http://pudge.wang:3000/api/cities/list').then((res) => {
      setCts(res.cts);
    });
  }, []);

  const PaginationChange = (page: number, pageSize: number) => {
    setPageSize(pageSize);
    setCurrentPage(page);
  };

  const search = () => {
    // console.log(form.getFieldsValue());
    setSearchObj(form.getFieldsValue());
  };

  const reset = () => {
    form.resetFields();
    setSearchObj({});
  };

  const confirm = (record: any) => {
    request
      .post('http://pudge.wang:3000/api/cities/manage/del', {
        data: {
          id: record._id,
        },
      })
      .then((res) => {
        if (res.status === 0) {
          message.success('删除成功');
          // 再次获取数据
          request
            .post('http://pudge.wang:3000/api/cities/manage/list', {
              data: {
                page_size: pageSize,
                current_page: currentPage,
                ...searchObj,
              },
            })
            .then((res) => {
              const result = res.result;
              const data = result.map((item: any) => {
                return {
                  ...item,
                  key: item._id,
                };
              });
              setDataSource(data);
              setTotal(res.total);
            });
        }
      });
  };

  const handleOpen = () => {
    form2.resetFields();
    setIsModalVisible(true);
  };

  const handleOk = () => {
    // setIsModalVisible(false);
    // console.log(form2.getFieldsValue());
    form2
      .validateFields()
      .then((values) => {
        // console.log(values);
        request
          .post('http://pudge.wang:3000/api/cities/manage/add', {
            data: {
              ...values,
              openTime: new Date(values.openTime).getTime(),
              handleTime: new Date().getTime(),
            },
          })
          .then((res) => {
            if (res.status === 0) {
              message.success('新增成功');
              setIsModalVisible(false);
              request
                .post('http://pudge.wang:3000/api/cities/manage/list', {
                  data: {
                    page_size: pageSize,
                    current_page: currentPage,
                    ...searchObj,
                  },
                })
                .then((res) => {
                  const result = res.result;
                  const data = result.map((item: any) => {
                    return {
                      ...item,
                      key: item._id,
                    };
                  });
                  setDataSource(data);
                  setTotal(res.total);
                });
            }
          });
      })
      .catch((errorInfo) => {
        return errorInfo;
      });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <Space direction="vertical" style={{ display: 'flex' }}>
      <Card>
        <Form form={form} name="horizontal_login" layout="inline">
          <Form.Item name="city" label="城市">
            <Select style={{ width: 120 }} allowClear>
              {cts.map((item: any) => {
                return (
                  <Select.Option value={item.nm} key={item.id}>
                    {item.nm}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item name="useCar" label="用车模式">
            <Select style={{ width: 120 }} allowClear>
              <Select.Option value="1">禁停区</Select.Option>
              <Select.Option value="2">停车点</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="operating" label="运营模式">
            <Select style={{ width: 120 }} allowClear>
              <Select.Option value="1">自营</Select.Option>
              <Select.Option value="2">加盟</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" onClick={search}>
                搜索
              </Button>
              <Button onClick={reset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card
        title="城市管理"
        extra={
          <Button type="primary" onClick={handleOpen}>
            新增
          </Button>
        }
      >
        <Table dataSource={dataSource} columns={columns} pagination={false} />
        <Pagination
          defaultCurrent={1}
          total={total}
          style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}
          onChange={PaginationChange}
        />
      </Card>

      <Modal
        title="新增城市"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form2}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
        >
          <Form.Item
            label="城市"
            name="city"
            rules={[{ required: true, message: '请选择城市!' }]}
          >
            <Select allowClear>
              {cts.map((item: any) => {
                return (
                  <Select.Option value={item.nm} key={item.id}>
                    {item.nm}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            name="useCar"
            label="用车模式"
            rules={[{ required: true, message: '请选择用车模式!' }]}
          >
            <Select allowClear>
              <Select.Option value="1">禁停区</Select.Option>
              <Select.Option value="2">停车点</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="operating"
            label="运营模式"
            rules={[{ required: true, message: '请选择运营模式!' }]}
          >
            <Select allowClear>
              <Select.Option value="1">自营</Select.Option>
              <Select.Option value="2">加盟</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="admin"
            label="管理员"
            rules={[{ required: true, message: '请输入管理员!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="openTime"
            label="开通时间"
            rules={[{ required: true, message: '请选择开通时间!' }]}
          >
            <DatePicker locale={locale} />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  );
};

export default Index;
